from fastapi import APIRouter, Query, HTTPException, Depends, UploadFile, File
from datetime import datetime
from typing import Optional
from sqlalchemy.orm import Session
import traceback  # 添加traceback导入
from loguru import logger
# 导入服务和模型
from ..schemas.message import MessageCreate, MessageDetail
from ..schemas.common import APIResponse
from ..db.session import get_db
from ..db.models.user import User
from ..utils.security import get_current_user
from ..services.message import MessageService
from ..api.ws import ws_handler  # 导入WebSocket处理器
from app.services.file import FileService
from ..db.models.chat import Message as DBMessage, Room, RoomMember

# 初始化路由
router = APIRouter(prefix="/message", tags=["消息管理"])

@router.get("/page/{id}", summary="分页获取消息记录")
async def get_message_page(
    id: str,
    roomId: int = Query(..., description="会话房间ID"),
    lastId: Optional[str] = Query(None, description="上一页最后一条消息ID"),
    size: int = Query(10, description="每页消息数量"),
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """根据房间ID分页获取消息记录"""
    # 解析lastId参数
    last_id = MessageService.parse_last_id(lastId)
    
    # 验证房间访问权限
    room, _ = MessageService.verify_room_access(db, roomId, current_user.id)
    
    # 获取消息列表
    messages = MessageService.get_messages(db, roomId, last_id, size)
    
    # 返回成功响应 - 确保符合前端期望的格式
    return APIResponse(
        code=200,
        message="获取消息记录成功",
        data=messages
    )

@router.post("/create", summary="发送消息")
async def send_message(
    message: MessageCreate,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """发送消息接口"""
    try:
        logger.info("消息发送")
        
        # 验证房间访问权限
        room, room_member = MessageService.verify_room_access(db, message.roomId, current_user.id)
        
        # 创建消息
        new_message = MessageService.create_message(
            db=db,
            room_id=message.roomId,
            sender_id=current_user.id,
            msg_type=message.type,
            content=message.content
        )
        
        # 获取发送者信息
        sender = db.query(User).filter(User.id == current_user.id).first()
        
        # 格式化消息
        message_detail = MessageService.format_message(new_message, sender)
        
        # 获取好友/群组信息
        friend, group = MessageService.get_room_context(db, room, current_user.id)
        
        # 构造返回数据
        response_data = {
            "message": message_detail,
            "roomId": message.roomId
        }
        
        # 根据房间类型处理消息发送
        if room.type == 0:  # 私聊
            # 获取接收者ID
            other_member = db.query(RoomMember).filter(
                RoomMember.room_id == room.id,
                RoomMember.user_id != current_user.id
            ).first()
            if other_member:
                # 通过WebSocket发送消息给接收者
                success = await MessageService.notify_message(
                    ws_handler,
                    other_member.user_id,
                    message.roomId,
                    message_detail,
                    friend,  # 这里传递friend对象
                    is_group=False
                )
                if not success:
                    logger.warning(f"私聊消息WebSocket发送失败，消息已加入重试队列: user_id={other_member.user_id}")
        else:  # 群聊
            # 获取群成员列表（除了发送者）
            group_members = db.query(RoomMember).filter(
                RoomMember.room_id == room.id,
                RoomMember.user_id != current_user.id
            ).all()
            
            # 向所有群成员发送消息
            for member in group_members:
                success = await MessageService.notify_message(
                    ws_handler,
                    member.user_id,
                    message.roomId,
                    message_detail,
                    group,  # 这里传递group对象
                    is_group=True
                )
                if not success:
                    logger.warning(f"群聊消息WebSocket发送失败，消息已加入重试队列: user_id={member.user_id}")
        
        return {
            "code": 200,
            "message": "发送成功",
            "data": response_data
        }
        
    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=500, detail={"message": f"发送消息失败: {str(e)}"})
